package cron_ser

import (
	"context"
	"encoding/json"
	"github.com/olivere/elastic/v7"
	"giv-vue-blog/global"
	"giv-vue-blog/models"
	"giv-vue-blog/service/redis_ser"
)

// SyncArticleData 同步文章数据到es
func SyncArticleData() {
	//1 查看全部es数据  为后面的数据更新做准备
	result, err := global.EsClient.Search(models.ArticleModel{}.Index()).
		Query(elastic.NewMatchAllQuery()).
		Size(1000).
		Do(context.Background())
	if err != nil {
		global.Log.Error(err)
		return
	}
	//2 拿到redis中的缓存数据
	diggInfo := redis_ser.NewDigg().GetInfo()
	lookInfo := redis_ser.NewArticleLook().GetInfo()
	commentInfo := redis_ser.NewComment().GetInfo()
	for _, hit := range result.Hits.Hits {
		var article models.ArticleModel
		err = json.Unmarshal(hit.Source, &article)
		if err != nil {
			global.Log.Error(err)
			return
		}
		digg := diggInfo[hit.Id]
		look := lookInfo[hit.Id]
		comment := commentInfo[hit.Id]
		//3 计算新数据 之前的数据+缓存中的数据
		newDigg := article.DiggCount + digg
		newLook := article.LookCount + look
		newComment := article.CommentCount + comment
		//4 判断数据是否有变化  无变化则继续 有变化则更新
		if digg == 0 &&
			look == 0 &&
			comment == 0 {
			global.Log.Infof("%s无变化", article.Title)
			continue
		}
		//5 更新
		_, err = global.EsClient.Update().Index(models.ArticleModel{}.Index()).
			Id(hit.Id).Doc(map[string]int{
			"digg_count":    newDigg,
			"comment_count": newComment,
			"look_count":    newLook,
		}).Do(context.Background())
		if err != nil {
			global.Log.Error(err)
			continue
		}
		global.Log.Infof("%s 更新成功 点赞数: %d 评论数: %d 浏览量: %d ", article.Title, newDigg, newComment, newLook)
	}
	//6 清除redis中的数据
	redis_ser.NewDigg().Clear()
	redis_ser.NewArticleLook().Clear()
	redis_ser.NewComment().Clear()
}
